<?php

class Users_EditAction extends SrsUsersBaseAction
{
	public function getCredentials()
	{
		return 'users.edit';
	}
	
	public function executeRead(AgaviRequestDataHolder $rd)
	{
		$this->setAttribute('roles', $this->getAvailableRoles());

		return 'Input';
	}

	public function executeWrite(AgaviRequestDataHolder $rd)
	{
		$userData = $rd->getParameter('user');

		$roles = $this->getAvailableRoles();

		$this->setAttribute('roles', $roles);

		if (!array_key_exists($userData['role'], $roles))
		{
			$this->addError('unknown_role', array('user[role]'), 'Podana rola nie istnieje.');

			return 'Error';
		}

		$user = Doctrine_Query::create()
		        ->from('User')
			      ->where('id=?', $rd->getParameter('id'))
					  ->fetchOne();

		if (!empty($userData['password']))
		{
			$user->password = hash('sha256', $userData['password']);
		}
		
		$user->email  = $userData['email'];
		$user->role   = $userData['role'];
		$user->name   = $userData['name'];
		$user->active = $userData['active'] === 1;
		$user->phone  = $userData['phone'];

		try
		{
			$user->save();
		}
		catch (Exception $x)
		{
			$this->addError('email_taken', 'user[email]', 'Podany adres e-mail jest już wykorzystywany.');

			return 'Error';
		}

		$this->setAttribute('user', $user->id);

		return 'Success';
	}

	private function getAvailableRoles()
	{
		return $this->getContext()->getUser()->getAvailableRoles();
	}
}